package com.cql.framework.config.security.service;


import com.cql.common.core.DO.UserDO;
import com.cql.common.core.security.LoginUser;
import com.cql.common.enums.UserStatus;
import com.cql.common.utils.StringUtils;
import com.cql.service.business.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author cql
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;


    @Autowired
    private PermissionService permissionService;

    /**
     * 根据用户名查询用户信息，这个用户名是在登录的时候，通过下面这个方法传过来的
     * AuthenticationManager
     * .authenticate(
     * new UsernamePasswordAuthenticationToken(username, password)
     * )
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        /**
         * 1.判断用户是否存在
         * 2.判断用户账号是否可用
         */
        UserDO user = userService.getUserByAccount(account);
        if (StringUtils.isNull(user)) {
            logger.info("登录用户：{} 不存在.", account);
            throw new UsernameNotFoundException("登录用户：" + account + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDeleted())) {
            logger.info("登录用户：{} 已被删除.", account);
            /**
             * 抛出自定义异常，全局处理
             */
            throw new RuntimeException("对不起，您的账号：" + account + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            logger.info("登录用户：{} 已被停用.", account);
            /**
             * 抛出自定义异常，全局处理
             */
            throw new RuntimeException("对不起，您的账号：" + account + " 已停用");
        }

        return createLoginUser(user);
    }

    /**
     * 查询用户信息
     *
     * @param user
     * @return
     */
    private UserDetails createLoginUser(UserDO user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUserDO(user);

        /**
         * 用户权限信息
         */
        loginUser.setPermissions(permissionService.getMenuPermission(user));

        /**
         * 用户角色信息
         */
        loginUser.setRoles(permissionService.getRolePermission(user));

        return loginUser;
    }


}
